package com.shiyi.shiyiaicodefather.manage;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.shiyi.shiyiaicodefather.coinfig.CosClientConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
@Slf4j
public class CosManager {

  @Resource
  private CosClientConfig clientConfig;
  @Resource
  private COSClient cosClient;

  /**
   * 上传对象
   *
   * @param key  唯一键
   * @param file 文件
   * @return 上传结果
   */
  public PutObjectResult putObject(String key, File file) {
    PutObjectRequest putObjectRequest = new PutObjectRequest(clientConfig.getBucket(), key, file);
    return cosClient.putObject(putObjectRequest);
  }

  /**
   * 上传文件到 COS 并返回访问 URL
   *
   * @param key  COS对象键（完整路径）
   * @param file 要上传的文件
   * @return 文件的访问URL，失败返回null
   */
  public String uploadFile(String key, File file) {
    PutObjectResult putObjectResult = putObject(key, file);
    if (putObjectResult != null) {
      String url = String.format("%s%s", clientConfig.getHost(), key);
      log.info("文件上传成功，访问URL：{}", url);
      return url;
    }
    log.error("文件上传COS失败，返回结果为空");
    return null;
  }

}
